#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/10/31 8:18
# @Author  : zhaowp1109
# @File    : goods_api.py
# @Description :
from typing import Any, Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.api import deps
from app.schemas.goods import ItemSearch, ItemSku
from app.schemas.base import RespListSchema, RespDetailSchema, BaseHeader
from app.core.constants import ResponseMessage,ResponseCode
from app.utils.open_api import item_search, item_get
from app.utils.sku_parse import taobao_sku_analysis
from urllib.parse import urlparse, parse_qs, unquote
from app.db.mongo_session import client

from app.core.logger import logger
from app.api.deps import get_headers
from bson.objectid import ObjectId
import json

router = APIRouter()


def is_valid_url(url):
    parsed = urlparse(url)
    if parsed.scheme and parsed.netloc:
        # if url.startswith("http://") or url.startswith("https://"):
        return True
    else:
        return False


def parse_url(url):
    channel = ""
    cid = ""
    store_id = ""
    return channel, cid, store_id


@router.get("/search", name="商品搜索/详情页/链接/关键字", response_model=RespDetailSchema)
async def search(page: Optional[int] = Query(default=1, example=1, description="页码", title="分页"),
                 q: str = Query(default="", example="T恤", description="店铺、商品链接,搜索关键词", title="搜索条件"),
                 header: BaseHeader = Depends(get_headers)) -> Any:
    keyword = unquote(q.strip())
    logger.info(f'keyword:{keyword}')
    # 根据语言确定数据源
    lang = header.lang
    item_coll_name = f"item_{lang}"
    item_search_name = f"item_search_{lang}"
    item_properties_coll = f"item_properties_{lang}"

    if not keyword:
        return RespDetailSchema(data=[])
    is_url = is_valid_url(keyword)
    if is_url:
        # 淘宝天猫商品链接
        if keyword.__contains__(".taobao.") or keyword.__contains__(".tmall."):
            parse_result = urlparse(keyword)
            params = parse_qs(parse_result.query)
            item_id = params.get("id")
            if item_id and isinstance(item_id, list):
                num_iid = item_id[0]
                # 从mongo数据库查询
                item_data = await client.do_find_one(item_coll_name, {"channel": "taobao", "num_iid": num_iid})
                if not item_data:
                    item_data = item_get(num_iid)
                    if item_data and item_data.get('error', '') == "":
                        # 从API获取数据,然后更新到商品数据库中
                        item_dict = item_data.get("item")
                        item_dict['channel'] = "taobao"

                        await client.do_insert_one(item_coll_name, item_dict)
                        props_list, skus = taobao_sku_analysis(item_dict)
                        skus_id = {v.get('sku_id'): v for v in props_list.values()}
                        object_id = item_dict.pop("_id")
                        await client.do_insert_one(item_properties_coll, {
                            "props_list": props_list,
                            "skus": skus,
                            "skus_id": skus_id,
                            "item_id": str(object_id),
                            "num_iid": item_dict.get("num_iid"),
                            "channel": item_dict.get("channel"),
                            "props_img": item_dict.get("props_img")
                        })
                        return RespDetailSchema(data=item_dict)
                    else:
                        return RespDetailSchema(data=item_data)
                else:
                    return RespDetailSchema(data=item_data)
        else:
            return RespDetailSchema(data=[])
    else:
        _items = item_search(q=keyword, page=page, lang=lang)
        return RespDetailSchema(data=_items)
    return RespDetailSchema(data=[])

@router.get("/detail", name="商品详情", response_model=RespDetailSchema)
async def goods_detail(num_iid: str = Query(example="", description="多商品ID", title="多商品ID"),
                       channel: str = Query(default="taobao",example="taobao",description="商品渠道", title="商品渠道"),
                       header: BaseHeader = Depends(get_headers)) -> Any:
    lang = header.lang
    num_iid = num_iid.strip()
    item_coll_name = f"item_{lang}"
    item_properties_coll = f"item_properties_{lang}"
    item_data = await client.do_find_one(item_coll_name,
                                         {"channel":channel,"num_iid": num_iid})
    if not item_data:
        item_data = item_get(num_iid)
        if item_data and item_data.get('error', '') == "":
            # 从API获取数据,然后更新到商品数据库中
            item_dict = item_data.get("item")
            item_dict['channel'] = channel
            await client.do_insert_one(item_coll_name, item_dict)
            props_list, skus = taobao_sku_analysis(item_dict)
            skus_id = {v.get('sku_id'): v for v in props_list.values()}
            object_id = item_dict.pop("_id")
            await client.do_insert_one(item_properties_coll, {
                "props_list": props_list,
                "skus": skus,
                "skus_id": skus_id,
                "item_id": str(object_id),
                "num_iid": item_dict.get("num_iid"),
                "channel": item_dict.get("channel"),
                "props_img": item_dict.get("props_img")
            })
            return RespDetailSchema(data=item_dict)
        else:
            return RespDetailSchema(code=ResponseCode.GOODS_CODES.NOT_FOUND,message=ResponseMessage.get_message(ResponseCode.GOODS_CODES.NOT_FOUND,lan=lang))
    else:
        return RespDetailSchema(data=item_data)

#
# @router.get("/checkurl/", name="商品搜索/关键字校验", response_model=RespDetailSchema)
# async def check_string(s: str = Query(default="", description="输入关键字", title="输入关键字")):
#     parsed = urlparse(s)
#     if parsed.scheme and parsed.netloc:
#         return RespDetailSchema(data={"is_url": True, "origin_url": s})
#     return RespDetailSchema(data={"is_url": False, "origin_url": s})


@router.post("/sku", name="商品sku信息", response_model=RespDetailSchema)
async def sku_detail(item_sku: ItemSku, header: BaseHeader = Depends(get_headers)) -> Any:
    lang = header.lang
    item_properties_coll = f"item_properties_{lang}"
    sku_data = await client.do_find_one(item_properties_coll,
                                        {"channel": item_sku.channel, "num_iid": item_sku.num_iid})
    return RespDetailSchema(data=sku_data)


# @router.get("/property",name="商品属性")
def property(db: Session = Depends(deps.get_db)) -> Any:
    return None


# @router.get("/description",name="商品详情")
def description(db: Session = Depends(deps.get_db)) -> Any:
    return None


# @router.get("/store",name="店铺信息")
def store_info(db: Session = Depends(deps.get_db)) -> Any:
    return None
